/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.mgt.server.service.power.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.github.yulichang.repository.JoinCrudRepository;
import com.iwindplus.boot.domain.enums.BizCodeEnum;
import com.iwindplus.boot.domain.enums.EnableStatusEnum;
import com.iwindplus.boot.domain.exception.BizException;
import com.iwindplus.boot.redis.manager.SerialNumManager;
import com.iwindplus.mgt.domain.constant.MgtConstant;
import com.iwindplus.mgt.domain.dto.power.RoleDTO;
import com.iwindplus.mgt.domain.dto.power.RoleEditDTO;
import com.iwindplus.mgt.domain.dto.power.RoleSaveDTO;
import com.iwindplus.mgt.domain.dto.power.RoleSearchDTO;
import com.iwindplus.mgt.domain.enums.MgtCodeEnum;
import com.iwindplus.mgt.domain.enums.MgtCodePrefixEnum;
import com.iwindplus.mgt.domain.vo.power.RoleBaseCheckedVO;
import com.iwindplus.mgt.domain.vo.power.RoleBaseVO;
import com.iwindplus.mgt.domain.vo.power.RoleExtendVO;
import com.iwindplus.mgt.domain.vo.power.RolePageVO;
import com.iwindplus.mgt.domain.vo.power.RoleVO;
import com.iwindplus.mgt.server.model.power.RoleDO;
import com.iwindplus.mgt.server.mapper.power.RoleMapper;
import com.iwindplus.mgt.server.service.power.PositionRoleService;
import com.iwindplus.mgt.server.service.power.RoleMenuService;
import com.iwindplus.mgt.server.service.power.RoleService;
import com.iwindplus.mgt.server.service.power.UserRoleService;
import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 角色业务层接口实现类.
 *
 * @author zengdegui
 * @since 2018/9/1
 */
@Slf4j
@Service
@CacheConfig(cacheNames = {"role"})
@Transactional(rollbackFor = Exception.class)
public class RoleServiceImpl extends JoinCrudRepository<RoleMapper, RoleDO> implements RoleService {

    @Resource
    private SerialNumManager serialNumManager;

    @Resource
    private RoleMenuService roleMenuService;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private PositionRoleService positionRoleService;

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleMenu"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleResource"}, allEntries = true),
            @CacheEvict(cacheNames = {"menu"}, allEntries = true),
            @CacheEvict(cacheNames = {"positionRole"}, allEntries = true),
            @CacheEvict(cacheNames = {"position"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"user"}, allEntries = true),
            @CacheEvict(cacheNames = {"userGroup"}, allEntries = true),
        }
    )
    @Override
    public boolean save(RoleSaveDTO entity) {
        entity.setStatus(EnableStatusEnum.ENABLE);
        entity.setBuildInFlag(Boolean.FALSE);
        this.getNameIsExist(entity.getName().trim(), entity.getOrgId());
        if (CharSequenceUtil.isBlank(entity.getCode())) {
            entity.setCode(this.serialNumManager.getSerialNum(MgtCodePrefixEnum.ROLE_PREFIX.getValue()));
        } else {
            if (entity.getCode().startsWith(MgtCodePrefixEnum.ROLE_PREFIX.getValue())) {
                throw new BizException(MgtCodeEnum.ROLE_PREFIX_ERROR);
            }
        }
        this.getCodeIsExist(entity.getCode().trim(), entity.getOrgId());
        entity.setSeq(this.getNextSeq(entity.getOrgId()));
        if (Boolean.TRUE.equals(entity.getDefaultFlag())) {
            this.editCancelDefault(null, entity.getOrgId());
        }
        final RoleDO model = BeanUtil.copyProperties(entity, RoleDO.class);
        boolean data = super.save(model);
        entity.setId(model.getId());
        Long roleId = entity.getId();
        // 角色菜单关系表维护
        this.roleMenuService.editBatchMenu(roleId, entity.getMenuIds());
        return data;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleMenu"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleResource"}, allEntries = true),
            @CacheEvict(cacheNames = {"menu"}, allEntries = true),
            @CacheEvict(cacheNames = {"positionRole"}, allEntries = true),
            @CacheEvict(cacheNames = {"position"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"user"}, allEntries = true),
            @CacheEvict(cacheNames = {"userGroup"}, allEntries = true),
        }
    )
    @Override
    public List<RoleVO> saveBatchInit(List<RoleDTO> entities) {
        List<RoleVO> resultList = new ArrayList<>(10);
        AtomicReference<Integer> seq = new AtomicReference<>();
        AtomicBoolean flag = new AtomicBoolean(true);
        List<RoleDTO> saveList = new ArrayList<>(10);
        List<RoleDTO> existList = new ArrayList<>(10);
        entities.forEach(entity -> {
            final RoleDO data = super.getOne(Wrappers.lambdaQuery(RoleDO.class)
                .eq(RoleDO::getName, entity.getName())
                .eq(RoleDO::getOrgId, entity.getOrgId()));
            if (Objects.isNull(data)) {
                if (flag.get()) {
                    seq.set(this.getNextSeq(entity.getOrgId()));
                    flag.set(false);
                }
                entity.setSeq(seq.getAndSet(seq.get() + 1));
                saveList.add(entity);
            } else {
                final RoleDTO dto = BeanUtil.copyProperties(data, RoleDTO.class);
                existList.add(dto);
            }
        });
        if (CollUtil.isNotEmpty(saveList)) {
            final List<RoleDO> doList = BeanUtil.copyToList(saveList, RoleDO.class);
            super.saveBatch(doList, DEFAULT_BATCH_SIZE);
            final List<RoleVO> voList = BeanUtil.copyToList(doList, RoleVO.class);
            resultList.addAll(voList);
        }
        if (CollUtil.isNotEmpty(existList)) {
            final List<RoleVO> voList = BeanUtil.copyToList(existList, RoleVO.class);
            resultList.addAll(voList);
        }
        return resultList;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleMenu"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleResource"}, allEntries = true),
            @CacheEvict(cacheNames = {"menu"}, allEntries = true),
            @CacheEvict(cacheNames = {"positionRole"}, allEntries = true),
            @CacheEvict(cacheNames = {"position"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"user"}, allEntries = true),
            @CacheEvict(cacheNames = {"userGroup"}, allEntries = true),
        }
    )
    @Override
    public boolean removeByIds(List<Long> ids) {
        List<RoleDO> list = super.listByIds(ids);
        if (CollUtil.isEmpty(list)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        boolean match = list.stream().anyMatch(RoleDO::getBuildInFlag);
        if (Boolean.TRUE.equals(match)) {
            throw new BizException(BizCodeEnum.HAS_BUILD_IN_DATA);
        }
        this.userRoleService.removeByRoleIds(ids);
        this.roleMenuService.removeByRoleIds(ids);
        this.positionRoleService.removeByRoleIds(ids);
        super.removeByIds(ids);
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleMenu"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleResource"}, allEntries = true),
            @CacheEvict(cacheNames = {"menu"}, allEntries = true),
            @CacheEvict(cacheNames = {"positionRole"}, allEntries = true),
            @CacheEvict(cacheNames = {"position"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"user"}, allEntries = true),
            @CacheEvict(cacheNames = {"userGroup"}, allEntries = true),
        }
    )
    @Override
    public boolean edit(RoleEditDTO entity) {
        // 编辑
        RoleDO data = super.getById(entity.getId());
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (Boolean.TRUE.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.BUILD_IN_DATA_NOT_OPERATE);
        }
        // 校验名称是否存在
        if (CharSequenceUtil.isNotBlank(entity.getName()) && !CharSequenceUtil.equals(data.getName(), entity.getName().trim())) {
            this.getNameIsExist(entity.getName().trim(), data.getOrgId());
        }
        if (CharSequenceUtil.isNotBlank(entity.getCode()) && !CharSequenceUtil.equals(data.getCode(), entity.getCode().trim())) {
            this.getCodeIsExist(entity.getCode().trim(), data.getOrgId());
        }
        if (Boolean.TRUE.equals(entity.getDefaultFlag())) {
            this.editCancelDefault(data.getId(), entity.getOrgId());
        }
        if (Objects.isNull(entity.getVersion())) {
            entity.setVersion(data.getVersion());
        }
        final RoleDO model = BeanUtil.copyProperties(entity, RoleDO.class);
        super.updateById(model);
        Long roleId = model.getId();
        // 角色资源关系表维护
        this.roleMenuService.editBatchMenu(roleId, entity.getMenuIds());
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleMenu"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleResource"}, allEntries = true),
            @CacheEvict(cacheNames = {"menu"}, allEntries = true),
            @CacheEvict(cacheNames = {"positionRole"}, allEntries = true),
            @CacheEvict(cacheNames = {"position"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"user"}, allEntries = true),
            @CacheEvict(cacheNames = {"userGroup"}, allEntries = true),
        }
    )
    @Override
    public boolean editStatus(Long id, EnableStatusEnum status) {
        RoleDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (Boolean.TRUE.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.BUILD_IN_DATA_NOT_OPERATE);
        }
        if (status.equals(data.getStatus())) {
            throw new BizException(BizCodeEnum.ALREADY_OPERATED);
        }
        RoleDO param = new RoleDO();
        param.setId(id);
        param.setStatus(status);
        param.setVersion(data.getVersion());
        super.updateById(param);
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleMenu"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleResource"}, allEntries = true),
            @CacheEvict(cacheNames = {"menu"}, allEntries = true),
            @CacheEvict(cacheNames = {"positionRole"}, allEntries = true),
            @CacheEvict(cacheNames = {"position"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"user"}, allEntries = true),
            @CacheEvict(cacheNames = {"userGroup"}, allEntries = true),
        }
    )
    @Override
    public boolean editDefault(Long id, Long orgId) {
        RoleDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (Boolean.TRUE.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.BUILD_IN_DATA_NOT_OPERATE);
        }
        this.editCancelDefault(id, orgId);
        RoleDO param = new RoleDO();
        param.setId(id);
        param.setDefaultFlag(true);
        param.setVersion(data.getVersion());
        super.updateById(param);
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleMenu"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleResource"}, allEntries = true),
            @CacheEvict(cacheNames = {"menu"}, allEntries = true),
            @CacheEvict(cacheNames = {"positionRole"}, allEntries = true),
            @CacheEvict(cacheNames = {"position"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"user"}, allEntries = true),
            @CacheEvict(cacheNames = {"userGroup"}, allEntries = true),
        }
    )
    @Override
    public boolean editBuildIn(Long id, Boolean buildInFlag) {
        RoleDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (buildInFlag.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.ALREADY_OPERATED);
        }
        RoleDO param = new RoleDO();
        param.setId(id);
        param.setBuildInFlag(buildInFlag);
        param.setVersion(data.getVersion());
        super.updateById(param);
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleMenu"}, allEntries = true),
            @CacheEvict(cacheNames = {"roleResource"}, allEntries = true),
            @CacheEvict(cacheNames = {"menu"}, allEntries = true),
            @CacheEvict(cacheNames = {"positionRole"}, allEntries = true),
            @CacheEvict(cacheNames = {"position"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"user"}, allEntries = true),
            @CacheEvict(cacheNames = {"userGroup"}, allEntries = true),
        }
    )
    @Override
    public Map<Long, Long> editInitToClient(Long orgId, Set<Long> roleIds) {
        Map<Long, Long> idMap = new HashMap<>(16);
        if (CollUtil.isEmpty(roleIds)) {
            return Collections.emptyMap();
        }
        final List<RoleDO> entities = super.list(Wrappers.lambdaQuery(RoleDO.class)
            .in(RoleDO::getId, roleIds).orderByAsc(RoleDO::getSeq));
        if (CollUtil.isEmpty(entities)) {
            return Collections.emptyMap();
        }
        final List<RoleDO> paramList = BeanUtil.copyToList(entities, RoleDO.class);
        this.buildInitList(orgId, paramList);
        final List<RoleDTO> dtoList = BeanUtil.copyToList(paramList, RoleDTO.class);
        final List<RoleVO> newList = this.saveBatchInit(dtoList);
        final List<RoleDO> doList = BeanUtil.copyToList(newList, RoleDO.class);
        this.buildIdMap(idMap, entities, doList);
        return idMap;
    }

    @Override
    public IPage<RolePageVO> page(RoleSearchDTO entity) {
        PageDTO<RoleDO> page = new PageDTO<>(entity.getCurrent(), entity.getSize());
        page.setOptimizeCountSql(Boolean.FALSE);
        page.setOptimizeJoinOfCountSql(Boolean.FALSE);
        return super.baseMapper.selectPageByCondition(page, entity);
    }

    @Cacheable(key = "#root.methodName + '_' + #p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public RoleExtendVO getDetailExtend(Long id) {
        return super.baseMapper.selectDetailById(id);
    }

    @Cacheable(key = "#root.methodName + '_' + #p0 + '_' + #p1", condition = "#p0 != null", unless = "#result == null")
    @Override
    public List<RoleBaseCheckedVO> listByUserId(Long orgId, Long userId) {
        List<RoleBaseCheckedVO> allList = super.baseMapper.selectListByOrgId(orgId);
        if (CollUtil.isEmpty(allList)) {
            return null;
        }
        if (Objects.nonNull(userId)) {
            List<RoleBaseCheckedVO> checkedList = super.baseMapper.selectListByUserId(orgId, userId);
            if (CollUtil.isNotEmpty(checkedList)) {
                allList = this.listWithChecked(allList, checkedList);
            }
        }
        return allList;
    }

    @Cacheable(key = "#root.methodName + '_' + #p0 + '_' + #p1", condition = "#p0 != null", unless = "#result == null")
    @Override
    public List<RoleBaseCheckedVO> listByPositionId(Long orgId, Long positionId) {
        List<RoleBaseCheckedVO> allList = super.baseMapper.selectListByOrgId(orgId);
        if (CollUtil.isEmpty(allList)) {
            return null;
        }
        if (Objects.nonNull(positionId)) {
            List<RoleBaseCheckedVO> checkedList = super.baseMapper.selectListByPositionId(orgId, positionId);
            if (CollUtil.isNotEmpty(checkedList)) {
                allList = this.listWithChecked(allList, checkedList);
            }
        }
        return allList;
    }

    @Cacheable(key = "#root.methodName + '_' + #p0 + '_' + #p1", condition = "#p0 != null && #p1 != null", unless = "#result == null")
    @Override
    public List<RoleBaseVO> listCheckedByUserId(Long orgId, Long userId) {
        List<RoleBaseVO> list = super.baseMapper.selectListCheckedByUserId(orgId, userId);
        if (CollUtil.isEmpty(list)) {
            return null;
        }
        return list.stream()
            .map(m -> new RoleBaseVO(m.getId(), m.getCode(), m.getName()))
            .sorted(Comparator.comparing(RoleBaseVO::getName))
            .collect(Collectors.toCollection(ArrayList::new));
    }

    @Cacheable(key = "#root.methodName", unless = "#result == null")
    @Override
    public List<Long> listDefault(Long orgId) {
        return super.listObjs(Wrappers.lambdaQuery(RoleDO.class)
            .eq(RoleDO::getDefaultFlag, Boolean.TRUE)
            .eq(RoleDO::getOrgId, orgId).select(RoleDO::getId), entity -> Long.valueOf(entity.toString()));
    }

    private void getNameIsExist(String name, Long orgId) {
        final LambdaQueryWrapper<RoleDO> queryWrapper = Wrappers.lambdaQuery(RoleDO.class)
            .eq(RoleDO::getName, name).eq(RoleDO::getOrgId, orgId);
        boolean result = SqlHelper.retBool(super.count(queryWrapper));
        if (result) {
            throw new BizException(MgtCodeEnum.NAME_EXIST);
        }
    }

    private void getCodeIsExist(String code, Long orgId) {
        final LambdaQueryWrapper<RoleDO> queryWrapper = Wrappers.lambdaQuery(RoleDO.class)
            .eq(RoleDO::getCode, code).eq(RoleDO::getOrgId, orgId);
        boolean result = SqlHelper.retBool(super.count(queryWrapper));
        if (result) {
            throw new BizException(MgtCodeEnum.CODE_EXIST);
        }
    }

    private Integer getNextSeq(Long orgId) {
        QueryWrapper<RoleDO> queryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(orgId)) {
            queryWrapper.lambda().eq(RoleDO::getOrgId, orgId);
        }
        queryWrapper.select("max(seq) as seq");
        Function<Object, Integer> function = val -> Integer.valueOf(val.toString());
        Integer data = super.getObj(queryWrapper, function);
        return Optional.ofNullable(data).map(x -> x + 1).orElse(1);
    }

    private List<RoleBaseCheckedVO> listWithChecked(List<RoleBaseCheckedVO> allList, List<RoleBaseCheckedVO> checkedList) {
        return allList.stream().peek(map -> checkedList.stream()
                .filter(m -> Objects.equals(m.getId(), map.getId())).forEach(m -> map.setChecked(m.getChecked())))
            .collect(Collectors.toCollection(ArrayList::new));
    }

    private void editCancelDefault(Long id, Long orgId) {
        List<RoleDO> defaultList = super.list(Wrappers.lambdaQuery(RoleDO.class)
            .eq(RoleDO::getDefaultFlag, Boolean.TRUE).eq(RoleDO::getOrgId, orgId)
            .select(RoleDO::getId, RoleDO::getVersion));
        if (CollUtil.isEmpty(defaultList)) {
            return;
        }
        if (Objects.nonNull(id)) {
            defaultList.removeIf(m -> id.equals(m.getId()));
        }
        if (CollUtil.isEmpty(defaultList)) {
            return;
        }
        List<RoleDO> list = defaultList.stream().map(m -> {
            RoleDO param = new RoleDO();
            param.setId(m.getId());
            param.setDefaultFlag(Boolean.FALSE);
            param.setVersion(m.getVersion());
            return param;
        }).collect(Collectors.toCollection(ArrayList::new));
        super.updateBatchById(list, DEFAULT_BATCH_SIZE);
    }

    private void buildInitList(Long orgId, List<RoleDO> entities) {
        entities.forEach(entity -> {
            entity.setId(null);
            entity.setVersion(0);
            entity.setOrgId(orgId);
            entity.setRemark(MgtConstant.REMARK_INIT);
        });
    }

    private void buildIdMap(Map<Long, Long> idMap, List<RoleDO> oldList, List<RoleDO> newList) {
        oldList.forEach(oldData -> newList.forEach(newData -> {
            if (oldData.getName().equals(newData.getName())) {
                idMap.put(oldData.getId(), newData.getId());
            }
        }));
    }
}
